//
//  ZYCTeacherDiningViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/12.
//

#import "ZYCTeacherDiningViewController.h"
#import <FSCalendar.h>
#import "BTImageTitleButton.h"
#import "ZYCTeacherDineCell.h"
#import "ZYCTeacherDineStatisticsViewController.h"
#import "NSDateExtra.h"
#import "ZYCScheduleRootSectionHeaderView.h"
#import "ZYCNoDataView.h"
#import "ZYCTeacherDineListModel.h"
#import "LunarFormatter.h"
#import "ZYCCalendarCell.h"
#import "UIButton+EnlargeEdge.h"


@interface ZYCTeacherDiningViewController ()<FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    void * _KVOContext;
}
@property (nonatomic, strong) FSCalendar *calendar;
@property (nonatomic, strong) NSCalendar *gregorian;
@property (nonatomic, strong) LunarFormatter *lunarFormatter;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIImageView *calendaerImgView;
@property (nonatomic, strong) BTImageTitleButton *statisticsButton;
@property (nonatomic, strong) UIButton *previousButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) NSDateFormatter *dateFormatter1;

@property (nonatomic, strong) MASConstraint *calenderHeightConstraint;
@property (nonatomic, strong) UIPanGestureRecognizer *scopeGesture;
@property (nonatomic, copy) NSString *month;
@property (nonatomic, copy) NSString *startDate;
@property (nonatomic, strong) NSMutableArray *calendarArr;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) ZYCNoDataView *noDataView;

@property (nonatomic, strong) NSArray *colorArray;
@end

@implementation ZYCTeacherDiningViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"教师就餐";
    [self setupContaints];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.statisticsButton];

    self.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    self.lunarFormatter = [[LunarFormatter alloc] init];
    [self addPanGestureRecognizer];
    // 监听KVO
    [self.calendar addObserver:self forKeyPath:@"scope" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:_KVOContext];
    self.month = [self.dateFormatter1 stringFromDate:[NSDate date]];
    self.startDate = [self.dateFormatter stringFromDate:[NSDate date]];
    // 获取日历数据
    [self loadTeacherDiningCalendar];
    // 获取日历列表
    [self loadTeacherDiningList];
}

// 获取日历数据
- (void)loadTeacherDiningCalendar{
    NSDictionary *params = @{
        @"month":self.month
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeacherDinerCalendaer requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = responseObject[@"body"];
                [self.calendarArr removeAllObjects];
                [self.calendarArr addObjectsFromArray:array];
                [self.calendar reloadData];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
// 教师就餐列表
- (void)loadTeacherDiningList{
    NSDictionary *params = @{
        @"startDate":self.startDate
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeacherDinerList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTeacherDineListModel class] json:responseObject[@"body"][@"list"]];
                [self.dataSource addObjectsFromArray:array];
                BOOL isShow = YES;
                for (ZYCTeacherDineListModel *model in array) {
                    if (model.times.count != 0) {
                        isShow = NO;
                    }
                }
                if (!isShow) {
                    self.tableView.hidden = NO;
                    self.noDataView.hidden = YES;
                }else{
                    self.tableView.hidden = YES;
                    self.noDataView.hidden = NO;
                }
                [self.tableView reloadData];
  
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}



#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (context == _KVOContext) {
        FSCalendarScope oldScope = [change[NSKeyValueChangeOldKey] unsignedIntegerValue];
        FSCalendarScope newScope = [change[NSKeyValueChangeNewKey] unsignedIntegerValue];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark - FSCalendarDataSource && FSCalendarDelegateAppearance

- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date{
    return [self.gregorian isDateInToday:date] ? @"今天" : nil;
}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    return [self.lunarFormatter stringFromDate:date];
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.calendarArr containsObject:dateString]) {
        cell.statusLabel.textColor = HEX_RGB(@"#41B166");
        cell.statusLabel.text = @"就餐";
        return cell;
    }
    return nil;
}

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated{
    [self.calenderHeightConstraint uninstall];
    [self.calendar mas_updateConstraints:^(MASConstraintMaker *make) {
        self.calenderHeightConstraint = make.height.mas_equalTo(CGRectGetHeight(bounds));
    }];
}
- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.calendarArr containsObject:dateString]) {
        return 1;
    }else {
        return 0;
    }
}
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    NSLog(@"did select date: %@",[self.dateFormatter stringFromDate:date]);
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    self.startDate = dateString;
    [self loadTeacherDiningList];
}

// 切换月份
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    NSString *dateString = [self.dateFormatter1 stringFromDate:calendar.currentPage];
    self.month = dateString;
    [self loadTeacherDiningCalendar];
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    ZYCTeacherDineListModel *model = self.dataSource[section];
    return model.times.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCTeacherDineCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeacherDineCell class]) forIndexPath:indexPath];
    ZYCTeacherDineListModel *model = self.dataSource[indexPath.section];
    NSString *title = model.times[indexPath.row];
    cell.titleString = title;
    [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
    return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 37.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZYCTeacherDineListModel *model = self.dataSource[section];
    ZYCScheduleRootSectionHeaderView *headerView = [[ZYCScheduleRootSectionHeaderView alloc] init];
    NSInteger i = section % 3;
    headerView.color = self.colorArray[i];
    headerView.dModel = model;
    return headerView;
}



#pragma mark - private method

- (void)addPanGestureRecognizer{
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.calendar action:@selector(handleScopeGesture:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 2;
    [self.view addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;
    // While the scope gesture begin, the pan gesture of tableView should cancel.
    [self.tableView.panGestureRecognizer requireGestureRecognizerToFail:panGesture];
}

- (void)setupContaints{
    [self.view addSubview:self.bgImageView];
    [self.view insertSubview:self.bgImageView atIndex:0];
    [self.view addSubview:self.calendaerImgView];
    [self.view addSubview:self.calendar];
    [self.calendar addSubview:self.previousButton];
    [self.calendar addSubview:self.nextButton];
    [self.view addSubview:self.tableView];
//
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(kNavBarAndStatusBarHeight);
        make.height.mas_equalTo(138.0f);
    }];

    [self.calendaerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(kNavBarAndStatusBarHeight);
        make.height.mas_equalTo(27.0f);
    }];
    
    [self.calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10.0f);
        make.right.equalTo(self.view).offset(-10.0f);
        make.top.equalTo(self.calendaerImgView.mas_centerY);
        self.calenderHeightConstraint = make.height.mas_equalTo(282);
    }];

    [self.previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.calendar).offset(95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];

    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.calendar).offset(-95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];


    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.calendar.mas_bottom);
    }];
    
    [self.previousButton setEnlargeEdgeWithTop:20 right:20 bottom:20 left:20];
    [self.nextButton setEnlargeEdgeWithTop:20 right:20 bottom:20 left:20];
}
#pragma mark - action
- (void)clickStatistics:(UIButton *)sender{
    ZYCTeacherDineStatisticsViewController *vc = [ZYCTeacherDineStatisticsViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)previousClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
}

-(void)nextClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
}

- (BTImageTitleButton *)statisticsButton {
    if (!_statisticsButton) {
        _statisticsButton = [[BTImageTitleButton alloc] init];
        [_statisticsButton setTitle:@"统计" forState:UIControlStateNormal];
        [_statisticsButton setImage:[UIImage imageNamed:@"tj"] forState:UIControlStateNormal];
        _statisticsButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_statisticsButton addTarget:self action:@selector(clickStatistics:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _statisticsButton;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTeacherDineCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeacherDineCell class])];
    }
    return _tableView;
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

- (NSDateFormatter *)dateFormatter1 {
    if (!_dateFormatter1) {
        _dateFormatter1 = [[NSDateFormatter alloc] init];
        [_dateFormatter1 setDateFormat:@"yyyy-MM"];
    }
    return _dateFormatter1;
}

- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}

- (FSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [[FSCalendar alloc] init];
        _calendar.delegate = self;
        _calendar.dataSource = self;
        _calendar.headerHeight = 50.0f;
        _calendar.appearance.headerMinimumDissolvedAlpha = 0;
        _calendar.backgroundColor = [UIColor whiteColor];
        _calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        _calendar.placeholderType = FSCalendarPlaceholderTypeNone; //只显示当前月份
        _calendar.appearance.headerDateFormat = @"yyyy年MM月";// 设置头部时间格式
        _calendar.appearance.weekdayTextColor = HEX_RGB(@"#62676A");//设置周字体颜色
        _calendar.appearance.headerTitleColor = HEX_RGB(@"#262A28");//设置头字体颜色
        _calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase|FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
        //        _calendar.appearance.eventDefaultColor = HEX_RGB(@"#CECECE");// 设置日期下的小点点颜色
        _calendar.appearance.selectionColor = FSCalendarStandardTodayColor; // 设置点击某日某日的颜色
        _calendar.appearance.todayColor = FSCalendarStandardTodayColor;// 设置今天颜色
        [_calendar registerClass:[ZYCCalendarCell class] forCellReuseIdentifier:@"cell"];
    }
    return _calendar;
}

- (UIButton *)previousButton {
    if (!_previousButton) {
        _previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previousButton setImage:[UIImage imageNamed:@"zuo"] forState:UIControlStateNormal];
        [_previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _previousButton;
}

- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setImage:[UIImage imageNamed:@"you"] forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ty"]];
    }
    return _bgImageView;
}

- (UIImageView *)calendaerImgView {
    if (!_calendaerImgView) {
        _calendaerImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rili"]];
    }
    return _calendaerImgView;
}


- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

- (NSArray *)colorArray {
    if (!_colorArray) {
        _colorArray = @[HEX_RGB(@"#EB9F28"),HEX_RGB(@"#39A85B"),HEX_RGB(@"#395AD2")];
    }
    return _colorArray;
}

- (NSMutableArray *)calendarArr {
    if (!_calendarArr) {
        _calendarArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _calendarArr;
}

- (void)dealloc{
    [self.calendar removeObserver:self forKeyPath:@"scope" context:_KVOContext];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
